// 引用路由
import Vue from 'vue';
import VueRouter from 'vue-router';
Vue.use(VueRouter);

// 定义（路由）组件。
import Index from '../views/Index.vue';
import Activity from '../views/Activity.vue';
import End from '../views/End.vue';
import EndNo from '../views/EndNoActivity.vue';
import Fail from '../views/Fail.vue';
import Winner from '../views/Winner.vue';
import RankingList from '../views/RankingList.vue';
import store from '../store/';
import wx from 'we-jssdk';
import wxConfig from '../filter/wxconfig.js';

// 定义路由
// 每个路由应该映射一个组件。 其中'component' 可以是
const routes = [
	{
		path: '/',
		redirect: '/index'
	}, 
	{
		path: '/index',
		name: 'index',
		component: Index
	}, {
		path: '/activity',
		name: 'activity',
		component: Activity
	}, {
		path: '/winner',
		name: 'winner',
		component: Winner
	}, {
		path: '/fail/:isFirst',
		name: 'fail',
		component: Fail
	}, {
		path: '/end/:isFirst',
		name: 'end',
		component: End
	},{
		path: '/endno/:noCurrent/:isFirst',
		name: 'endno',
		component: EndNo
	}, {
		path: '/rank',
		name: 'rank',
		component: RankingList
	}
]


// 创建 router 实例，然后传 `routes` 配置
const router = new VueRouter({
	// mode: 'history',
	routes, // （缩写）相当于 routes: routes
	scrollBehavior(to, from, savedPosition) {
		if (savedPosition) {
			return savedPosition
		} else {
			return {
				x: 0,
				y: 0
			}
		}
	}
});


// 钩子函数,必须执行next()
// 一些回退事件可以在这里面进行处理
router.beforeEach((to, from, next) => {
	_hmt.push(['_trackPageview', to.fullPath]);

	if (from.name === 'index') {
		store.commit('changeModuleTransitionName', 'fade');
	} else {
		store.commit('changeModuleTransitionName', 'slide-left');
	}
	// 在活动页面，返回直接关闭微信窗口
	if ((from.name === 'activity' || from.name === 'end' || from.name === 'endno' || from.name === 'winner') && to.name === 'index') {
		wx.closeWindow();
		return false;
	}

	if((from.name === 'winner' || from.name === 'fail') && (to.name === 'activity')){
		wx.closeWindow();
		return false;
	}

	//从结果页面或者结束页面，返回到活动主页面
	if ((from.name === 'winner' || from.name === 'fail' || from.name === 'end' || from.name === 'endno') &&  (to.name === 'fail' || to.name === 'activity')){
		store.commit('changeModuleTransitionName', 'slide-right');
	}

	// 从列表返回
	if(from.name === 'rank' && to.name === 'end'){
		store.commit('changeModuleTransitionName', 'slide-right');
	}

	next();
});

router.afterEach(route => {
	setTimeout(() => {
		wxConfig.init(store, route.name);
	}, 1000);
});

export default router;